package com.xnfh.network.interceptor

import com.xnfh.framework.log.LogUtil
import com.xnfh.network.constant.REQUEST_HEADER_TOKEN
import com.xnfh.network.constant.REQUEST_LOGIN_URL
import com.xnfh.network.manager.TokenManager
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/7 17:02
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/7 17:02
 * @UpdateRemark: 更新说明
 */
class TokenInterceptor: Interceptor {
    private val TAG = "TokenInterceptor"
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder()

        val response = chain.proceed(newBuilder.build())
        val url = request.url().toString()
        val host = request.url().host()

        // set-cookie maybe has multi, login to save cookie
        if (url.contains(REQUEST_LOGIN_URL)
            && response.headers(REQUEST_HEADER_TOKEN).isNotEmpty()
        ) {
            val cookies = response.headers().get(REQUEST_HEADER_TOKEN)
            cookies?.let { TokenManager.saveUserToken(it) }
            LogUtil.e("CookiesInterceptor:cookies:$cookies", tag = TAG)
        }
        return response
    }
}